package controllers;

import helpers.SessionHelper;
import helpers.StringHelper;

import java.io.IOException;
import java.rmi.ServerException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sun.security.provider.MD5;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import data.EmailData;
import data.UserData;
import debugs.UserDebug;
import forms.CaptchaForm;
import forms.UserForm;

import models.EmailModel;
import models.UserModel;

public class RegisterServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		
		TreeMap check = new TreeMap();
		UserModel user = new UserModel();
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		request.setAttribute("form", "add");
		
		try {
			request.getRequestDispatcher("/pages/form_user.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		HttpSession session = request.getSession();
		response.setCharacterEncoding("UTF-8");
		
		UserData uData = new UserData();
		UserModel user =  new UserModel();
		UserForm userForm = new UserForm();
		//CaptchaForm captchaForm = new CaptchaForm();
		TreeMap forms = (TreeMap) userForm.checkValid(request, user);
		user = (UserModel) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		//check = captchaForm.checkValid(request, check);
		
		if (check.size() == 0) {
			user.setPassword(StringHelper.md5(user.getPassword()));
			user.setStatus(2);
			uData.insert(user);
			
			//Insert to email model
			EmailData emailData = new EmailData();
			EmailModel email = emailData.getEmail(user.getUsername());
			if (email == null) {
				email = new EmailModel();
				email.setEmail(user.getUsername());
				email.setCity(user.getCity());
				emailData.insert(email);
			}
			
			//Save login to session
			session.setAttribute("user_logged_in", user);
			session.setAttribute("success", "Bạn đã đăng ký thành công");
			request.setAttribute("success", "Bạn đã đăng ký thành công");
			response.sendRedirect("/" + SessionHelper.getCurrentCity(request).getAlias());
			return;
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		request.setAttribute("form", "add");
		
		try {
			request.getRequestDispatcher("/pages/form_user.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
